import Access from '@/components/Access';
import Menu from '@/components/Form/Menu';
import HandleBtn from '@/components/HandleBar/btn';
import type { ActionType, ProFormInstance } from '@/components/Pro';
import { ModalForm, ProColumns, ProTable } from '@/components/Pro/';
import Tabs from '@/components/Tabs';
import { sysRoleControllerGetRoleMenus } from '@/services/ess/sysRole';
import {
  sysTenantControllerDelete,
  sysTenantControllerEditMenus as editMenus,
  sysTenantControllerExport,
  sysTenantControllerPageList,
  sysTenantControllerSaveBatch,
  sysTenantControllerSetStatus,
} from '@/services/ess/sysTenant';
import { getMenuList } from '@/utils/';
import { downloadFetch } from '@/utils/downloadFile';
import { Flex, Form, message, Modal, Space, Switch, Upload, type UploadProps } from 'antd';
import type { TableRowSelection } from 'antd/lib/table/interface';
import React, { ReactNode, useEffect, useMemo, useRef, useState } from 'react';
import { useIntl, useModel } from 'umi';
import Styles from '../index.less';
import AddModal from './components/AddModal';
import EditModal from './components/EditModal';
import { TenantryType } from './type';

const { confirm } = Modal;

// type ModalType = {
//   title: string;
//   content: React.ReactNode;
// };

const TenantryManager: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [messageApi, contextHolder] = message.useMessage();
  const tableRef = useRef<ActionType>();
  const proTableFormRef = useRef<ProFormInstance>();
  const [selectedColumns, setSelectedColumns] = useState<string[]>([]);
  const [menuModalOpen, handleMenuModalOpen] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState({});
  const intl = useIntl();
  const isEnglish = intl.locale === 'en-US';

  const [disabled, setDisabled] = useState(false);
  const [platformType, setPlatformType] = useState<'WEB' | 'APP'>('WEB');
  const [webMenuData, setWebMenuData] = useState([]);
  const [appMenuData, setAppMenuData] = useState([]);
  const [webSelectedIds, setWebSelectedIds] = useState<string[]>([]);
  const [appSelectedIds, setAppSelectedIds] = useState<string[]>([]);

  useEffect(() => {
    const fetchMenuData = async () => {
      try {
        const webData = await getMenuList(sysRoleControllerGetRoleMenus, { platformType: 'WEB' });
        const appData = await getMenuList(sysRoleControllerGetRoleMenus, { platformType: 'APP' });
        setWebMenuData(webData);
        setAppMenuData(appData);
      } catch (error) {
        console.error('Error fetching menu data:', error);
      }
    };
    fetchMenuData();
  }, []);
  // 更新站点信息
  const updateStationInfo = () => {
    initialState?.updateStationInfo?.(initialState).then((infos) => {
      if (infos) {
        setInitialState((s) => ({
          ...s,
          ...infos,
        }));
      }
    });
  };
  const handleEdit = (values: boolean) => {
    if (values) {
      tableRef?.current?.reloadAndRest?.();
      updateStationInfo();
    }
  };

  // useEffect(() => {
  //   (async () => {
  //     const data = await getMenuList();
  //     setMenuData(data);
  //   })();
  // }, []);
  const relieveFreeze = (token: boolean) => {
    if (token) {
      tableRef?.current?.reloadAndRest?.();
    }
  };
  /**
   *
   * @param switchVal
   * @param record
   */
  const handleSwitchStatus = (switchVal: boolean, record: API.SysTenant) => {
    confirm({
      title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
      content: intl.formatMessage({
        id: 'systemManagement.supplementary.doYouWantToChangeTheEnabledStatusOfThisData',
      }),
      onOk: async () => {
        const params: API.TenantSetStatusForm = {
          tenantIds: [record.tenantId],
          action: switchVal,
        } as any;
        const res = await sysTenantControllerSetStatus(params);
        if (res?.success) {
          messageApi.open({
            type: 'success',
            content: intl.formatMessage({ id: 'systemManagement.neddTochange.operationSuccess' }),
          });
          tableRef?.current?.reloadAndRest?.();
          updateStationInfo();
        }
      },
    });
  };

  const columns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.tenantName' }),
      dataIndex: 'tenantName',
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.tenantCode' }),
      dataIndex: 'tenantNo',
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.administrator' }),
      dataIndex: 'manager',
      render: (_: ReactNode, record: API.SysTenant) => <span>{record?.manager?.nickName}</span>,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.termOfValidity' }),
      dataIndex: 'expireTime',
      search: false,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.contactNumber' }),
      dataIndex: 'phone',
      render: (_: ReactNode, record: API.SysTenant) => <span>{record?.manager?.phone}</span>,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.creationTime' }),
      dataIndex: 'createTime',
      valueType: 'dateRange',
      width: 160,
      render: (_, record) => {
        return <span>{record.createTime}</span>;
      },
      search: {
        transform: (value) => {
          return {
            createStartTime: value[0],
            createEndTime: value[1],
          };
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.modificationTime' }),
      dataIndex: 'modifyTime',
      hideInSearch: true,
      width: 160,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.status' }),
      dataIndex: 'status',
      valueType: 'select',
      width: 80,
      //@ts-ignore
      valueEnum: new Map([
        ['', intl.formatMessage({ id: 'systemManagement.generalProcedure.all' })],
        [true, intl.formatMessage({ id: 'systemManagement.generalProcedure.enable' })],
        [false, intl.formatMessage({ id: 'systemManagement.generalProcedure.disable' })],
      ]),
      render: (_: ReactNode, record: API.SysTenant) => {
        return [
          <Access perm={'sys:tenant:setStatus'} key={'switchVal'}>
            <Switch
              checkedChildren={intl.formatMessage({
                id: 'systemManagement.generalProcedure.enable',
              })}
              unCheckedChildren={intl.formatMessage({
                id: 'systemManagement.generalProcedure.disable',
              })}
              defaultChecked={record.status}
              value={record.status}
              onChange={(checked) => {
                handleSwitchStatus(checked, record);
              }}
              // onClick={(checked) => {
              //   handleSwitchStatus(checked, record);
              // }}
            />
          </Access>,
        ];
      },
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.operation' }),
      hideInSearch: true,
      width: 200,
      fixed: 'right',
      render: (_: ReactNode, record: API.SysTenant) => {
        let formProps = JSON.parse(
          JSON.stringify({
            ...record,
            tenState: record.status,
            validity: [record.startTime, record.expireTime],
            manId: record.manager?.userName,
            manName: record.manager?.nickName,
            manState: record.manager?.status,
            manTel: record.manager?.phone,
            freeze: record?.manager?.freeze,
            userId: record?.manager?.userId,
          }),
        );

        return (
          <div>
            <Space>
              <Access perm={'sys:tenant:menu'} key={'menu'}>
                <a
                  onClick={() => {
                    handleMenuModalOpen(true);
                    setCurrentRow(record);
                  }}
                >
                  {intl.formatMessage({ id: 'systemManagement.generalProcedure.menuPermissions' })}
                </a>
              </Access>
              <Access perm={'sys:tenant:edit'} key={'edit'}>
                <EditModal
                  isEdit={false}
                  formProps={formProps}
                  handleEdit={handleEdit}
                  relieveFreeze={relieveFreeze}
                ></EditModal>
              </Access>
              <Access perm={'sys:tenant:info'} key={'info'}>
                <EditModal
                  isEdit={true}
                  formProps={formProps}
                  handleEdit={handleEdit}
                  relieveFreeze={relieveFreeze}
                ></EditModal>
              </Access>
              <Access perm={'sys:tenant:delete'} key={'del'}>
                <a
                  className="global-del-color"
                  onClick={() => {
                    confirm({
                      title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
                      content: intl.formatMessage({ id: 'global.delTip' }),
                      onOk() {
                        sysTenantControllerDelete([record.tenantId]).then((res) => {
                          if (res.success) {
                            messageApi.open({
                              type: 'success',
                              content: res.message,
                            });
                            tableRef?.current?.reloadAndRest?.();
                            updateStationInfo();
                          }
                        });
                      },
                    });
                  }}
                >
                  {intl.formatMessage({ id: 'systemManagement.generalProcedure.delete' })}
                </a>
              </Access>
            </Space>
          </div>
        );
      },
    },
  ];

  const selectionChange = (_: React.Key[], selectedRows: API.SysTenant[]) => {
    const tempArray: string[] = [];
    selectedRows.forEach((item: API.SysTenant) => {
      tempArray.push(item.tenantId as string);
    });
    setSelectedColumns(tempArray);
  };

  const handleRowSelection: TableRowSelection<TenantryType> = {
    onChange: selectionChange,
  };

  const handleAddSubmit = (values: boolean) => {
    if (values) {
      tableRef?.current?.reloadAndRest?.();
    }
  };
  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    showUploadList: false,
    customRequest: async (info) => {
      const form = new FormData();
      form.append('file', info.file);
      const res = await sysTenantControllerSaveBatch(form);
      if (res?.success) {
        message.success(`${info.file.name} ${intl.formatMessage({ id: 'global.iFileS' })}`);
        tableRef?.current?.reloadAndRest?.();
        return;
      }
      const msg = info?.file?.response?.message;
      message.error(
        `${info.file.name} ${intl.formatMessage({ id: 'global.iFileF' })} ${msg ? ',' + msg : ''}`,
      );
    },
  };

  useEffect(() => {
    if (currentRow?.sysMenus) {
      const webMenus = currentRow.sysMenus.filter((menu) => menu.platformType === 'WEB');
      const appMenus = currentRow.sysMenus.filter((menu) => menu.platformType === 'APP');

      setWebSelectedIds(webMenus.map((menu) => menu.menuId));
      setAppSelectedIds(appMenus.map((menu) => menu.menuId));
    }
  }, [currentRow]);

  const handleMenuSubmit = async (values: any) => {
    try {
      // 1. 检查 WEB 端是否有选择菜单
      if (!webSelectedIds.length) {
        message.warning(
          intl.formatMessage({
            id: 'systemManagement.menuManagementMenu.webMenuRequired',
          }),
        );
        // 切换到 WEB tab
        setPlatformType('WEB');
        return false;
      }

      // 2. 合并两个 tab 的选中状态
      const allSelectedIds = [...new Set([...webSelectedIds, ...appSelectedIds])];

      console.log('提交菜单权限:', {
        webSelectedIds,
        appSelectedIds,
        allSelectedIds,
      });

      const result = await editMenus(
        {
          tenantId: currentRow?.tenantId,
        },
        {
          type: values.type,
          menuIds: allSelectedIds,
        },
      );

      if (result.success) {
        message.success(
          intl.formatMessage({ id: 'systemManagement.requiredFields.menuEditSuccess' }),
        );
        handleMenuModalOpen(false); // 关闭弹窗
        tableRef?.current?.reloadAndRest?.();
        return true;
      }
      return false;
    } catch (error) {
      console.error('Error saving tenant menus:', error);
      return false;
    }
  };

  const menuFormItem = useMemo(() => {
    if (platformType === 'WEB') {
      return (
        <Form.Item
          name="webMenuIds"
          label={intl.formatMessage({ id: 'systemManagement.menuManagementMenu.selectMenu' })}
          style={{ flex: 1 }}
          labelCol={{ span: isEnglish ? 5 : 4 }}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'systemManagement.menuManagementMenu.meunRequire',
              }),
            },
          ]}
        >
          <Menu
            treeData={webMenuData}
            value={webSelectedIds}
            onChange={(ids) => {
              console.log('WEB Selected IDs:', ids);
              setWebSelectedIds(ids);
            }}
          />
        </Form.Item>
      );
    }
    return (
      <Form.Item
        name="appMenuIds"
        label={intl.formatMessage({ id: 'systemManagement.menuManagementMenu.selectMenu' })}
        style={{ flex: 1 }}
        labelCol={{ span: isEnglish ? 5 : 4 }}
        rules={[
          {
            required: false,
            message: intl.formatMessage({
              id: 'systemManagement.menuManagementMenu.meunRequire',
            }),
          },
        ]}
      >
        <Menu
          treeData={appMenuData}
          value={appSelectedIds}
          onChange={(ids) => {
            console.log('APP Selected IDs:', ids);
            setAppSelectedIds(ids);
          }}
        />
      </Form.Item>
    );
  }, [platformType, webMenuData, appMenuData, webSelectedIds, appSelectedIds, intl]);

  return (
    <>
      {contextHolder}
      <ProTable<API.sysTenantControllerPageListParams, API.PageParams>
        actionRef={tableRef}
        headerTitle={
          <div className={`${isEnglish ? Styles.table_header_title : ''}`}>
            {intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.tenantManagement' })}
          </div>
        }
        rowKey="tenantId"
        formRef={proTableFormRef}
        request={sysTenantControllerPageList}
        columns={columns}
        rowSelection={handleRowSelection}
        toolBarRender={() => [
          <Access perm={'sys:tenant:add'} key={'add'}>
            <AddModal handleAddSubmit={handleAddSubmit} />
          </Access>,
          <Access perm={'sys:tenant:add:batch'} key={'import'}>
            <Upload key="import" {...uploadProps}>
              <HandleBtn handleType="import">
                {intl.formatMessage({ id: 'systemManagement.generalProcedure.import' })}
              </HandleBtn>
            </Upload>
          </Access>,
          <Access perm={'sys:tenant:export'} key={'export'}>
            <HandleBtn
              handleType="export"
              key="export"
              onClick={() => {
                const formValue = proTableFormRef?.current?.getFieldFormatValue();
                const params: API.sysTenantControllerExportParams = {
                  tenantName: formValue?.tenantName,
                  tenantNo: formValue?.tenantNo,
                  managerId: formValue?.manager,
                  phoneNumber: formValue?.phone,
                  createTime: formValue?.createTime,
                  status: formValue?.status,
                };
                downloadFetch(sysTenantControllerExport, params);
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.export' })}
            </HandleBtn>
          </Access>,
          <Access perm={'sys:tenant:setStatus:batch'} key={'enable'}>
            <HandleBtn
              key="enable"
              handleType="enable"
              onClick={async () => {
                console.log('selectedColumns', selectedColumns);
                if (!selectedColumns?.length) {
                  message.warning(intl.formatMessage({ id: 'global.leastOne' }));
                  return;
                }
                if (disabled) return;
                setDisabled(true);
                confirm({
                  title: intl.formatMessage({
                    id: 'systemManagement.generalProcedure.batchEnable',
                  }),
                  content: `${intl.formatMessage({
                    id: 'systemManagement.neddTochange.siteTenantChage1',
                  })}${selectedColumns.length}${intl.formatMessage({
                    id: 'systemManagement.neddTochange.siteTenantChage2',
                  })}`,
                  async onOk() {
                    const res = await sysTenantControllerSetStatus({
                      tenantIds: selectedColumns,
                      action: true,
                    });
                    if (res.success) {
                      messageApi.open({
                        type: 'success',
                        content: res.message,
                      });
                      tableRef?.current?.reloadAndRest?.();
                      updateStationInfo();
                    }
                  },
                  afterClose: () => {
                    setDisabled(false);
                  },
                });
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchEnable' })}
            </HandleBtn>
          </Access>,
          <Access perm={'sys:tenant:setStatus:batch'} key={'disabled'}>
            <HandleBtn
              key="disabled"
              handleType="disabled"
              onClick={async () => {
                if (!selectedColumns?.length) {
                  message.warning(intl.formatMessage({ id: 'global.leastOne' }));
                  return;
                }
                if (disabled) return;
                setDisabled(true);
                confirm({
                  title: intl.formatMessage({
                    id: 'systemManagement.generalProcedure.batchDisable',
                  }),
                  content: `${intl.formatMessage({
                    id: 'systemManagement.neddTochange.siteTenantChage1',
                  })} ${selectedColumns.length}${intl.formatMessage({
                    id: 'systemManagement.neddTochange.siteTenantChage2',
                  })}`,
                  async onOk() {
                    const res = await sysTenantControllerSetStatus({
                      tenantIds: selectedColumns,
                      action: false,
                    });
                    if (res.success) {
                      messageApi.open({
                        type: 'success',
                        content: res.message,
                      });
                      tableRef?.current?.reloadAndRest?.();
                      updateStationInfo();
                    }
                  },
                  afterClose: () => {
                    setDisabled(false);
                  },
                });
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchDisable' })}
            </HandleBtn>
          </Access>,
          <Access perm={'sys:tenant:delete:batch'} key={'delete'}>
            <HandleBtn
              key="delete"
              handleType="delete"
              onClick={() => {
                if (!selectedColumns?.length) {
                  message.warning(intl.formatMessage({ id: 'global.leastOne' }));
                  return;
                }

                if (disabled) return;
                setDisabled(true);
                confirm({
                  title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
                  content: intl.formatMessage({
                    id: 'systemManagement.supplementary.dataCannotBeRestoredAfterDeletion',
                  }),
                  onOk() {
                    sysTenantControllerDelete(selectedColumns).then((res) => {
                      if (res.success) {
                        messageApi.open({
                          type: 'success',
                          content: res.message,
                        });
                        tableRef?.current?.reloadAndRest?.();
                        updateStationInfo();
                      }
                    });
                  },
                  afterClose: () => {
                    setDisabled(false);
                  },
                });
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchDelete' })}
            </HandleBtn>
          </Access>,
        ]}
      ></ProTable>
      <ModalForm
        modalProps={{
          destroyOnClose: true,
        }}
        title={intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.menuPermiscsions' })}
        initialValues={{
          ...currentRow,
          webMenuIds: currentRow.sysMenus?.map((menu) => menu.menuId),
          appMenuIds: currentRow.sysMenus?.map((menu) => menu.menuId),
        }}
        width="600px"
        labelCol={{
          flex: `0 0 100px`,
        }}
        style={{
          marginRight: 30,
        }}
        open={menuModalOpen}
        onOpenChange={handleMenuModalOpen}
        onFinish={handleMenuSubmit}
      >
        <Tabs
          activeKey={platformType}
          onChange={(key) => {
            setPlatformType(key as 'WEB' | 'APP');
          }}
          className={Styles.smallTabs}
          items={[
            {
              key: 'WEB',
              label: intl.formatMessage({
                id: 'systemManagement.menuManagementMenu.WEBPermissions',
              }),
            },
            {
              key: 'APP',
              label: intl.formatMessage({
                id: 'systemManagement.menuManagementMenu.APPPermissions',
              }),
            },
          ]}
        />
        <Flex style={{ width: '100%', marginInline: 4 }} key={platformType}>
          {menuFormItem}
        </Flex>
      </ModalForm>
    </>
  );
};

export default TenantryManager;
